package sto.orz.sql;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.dbcp.BasicDataSource;

import sto.orz.rptp.model.Datasource;

public class DBCPConnectionManager implements ConnectionManager {
	private Map<String, BasicDataSource> cache = new HashMap<String, BasicDataSource>();

	public Connection getConnection(Datasource ds) throws SQLException {
		String id = ds.getId();
		BasicDataSource datasource = cache.get(id);
		if (datasource == null) {
			String driver = ds.getDriver();
			String url = ds.getUrl();
			String username = ds.getUsername();
			String password = ds.getPassword();

			datasource = new BasicDataSource();
			datasource.setDriverClassName(driver);
			datasource.setUrl(url);
			datasource.setUsername(username);
			datasource.setPassword(password);
			cache.put(id, datasource);
		}
		return datasource.getConnection();
	}

	public void clearCache(Datasource ds) {
		cache.remove(ds.getId());
	}

}